{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# vrp_node_max"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/constraint_solver/vrp_node_max.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/ortools/constraint_solver/samples/vrp_node_max.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Vehicles Routing Problem (VRP).\n",
    "\n",
    "Each route as an associated objective cost equal to the max node value along the\n",
    "road multiply by a constant factor (4200)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from ortools.constraint_solver import routing_enums_pb2\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "\n",
    "def create_data_model():\n",
    "    \"\"\"Stores the data for the problem.\"\"\"\n",
    "    data = {}\n",
    "    data[\"distance_matrix\"] = [\n",
    "        # fmt: off\n",
    "      [0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662],\n",
    "      [548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210],\n",
    "      [776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754],\n",
    "      [696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358],\n",
    "      [582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244],\n",
    "      [274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708],\n",
    "      [502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480],\n",
    "      [194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856],\n",
    "      [308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514],\n",
    "      [194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468],\n",
    "      [536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354],\n",
    "      [502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844],\n",
    "      [388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730],\n",
    "      [354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536],\n",
    "      [468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194],\n",
    "      [776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798],\n",
    "      [662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0],\n",
    "        # fmt: on\n",
    "    ]\n",
    "    data[\"value\"] = [\n",
    "        0,  # depot\n",
    "        42,  # 1\n",
    "        42,  # 2\n",
    "        8,  # 3\n",
    "        8,  # 4\n",
    "        8,  # 5\n",
    "        8,  # 6\n",
    "        8,  # 7\n",
    "        8,  # 8\n",
    "        8,  # 9\n",
    "        8,  # 10\n",
    "        8,  # 11\n",
    "        8,  # 12\n",
    "        8,  # 13\n",
    "        8,  # 14\n",
    "        42,  # 15\n",
    "        42,  # 16\n",
    "    ]\n",
    "    assert len(data[\"distance_matrix\"]) == len(data[\"value\"])\n",
    "    data[\"num_vehicles\"] = 4\n",
    "    data[\"depot\"] = 0\n",
    "    return data\n",
    "\n",
    "\n",
    "\n",
    "def print_solution(data, manager, routing, solution):\n",
    "    \"\"\"Prints solution on console.\"\"\"\n",
    "    print(f\"Objective: {solution.ObjectiveValue()}\")\n",
    "    max_route_distance = 0\n",
    "    dim_one = routing.GetDimensionOrDie(\"One\")\n",
    "    dim_two = routing.GetDimensionOrDie(\"Two\")\n",
    "\n",
    "    for vehicle_id in range(data[\"num_vehicles\"]):\n",
    "        if not routing.IsVehicleUsed(solution, vehicle_id):\n",
    "            continue\n",
    "        index = routing.Start(vehicle_id)\n",
    "        plan_output = f\"Route for vehicle {vehicle_id}:\\n\"\n",
    "        route_distance = 0\n",
    "        while not routing.IsEnd(index):\n",
    "            one_var = dim_one.CumulVar(index)\n",
    "            one_slack_var = dim_one.SlackVar(index)\n",
    "            two_var = dim_two.CumulVar(index)\n",
    "            two_slack_var = dim_two.SlackVar(index)\n",
    "            plan_output += (\n",
    "                f\" N:{manager.IndexToNode(index)}\"\n",
    "                f\" one:({solution.Value(one_var)}, {solution.Value(one_slack_var)})\"\n",
    "                f\" two:({solution.Value(two_var)}, {solution.Value(two_slack_var)})\"\n",
    "                \" -> \"\n",
    "            )\n",
    "            previous_index = index\n",
    "            index = solution.Value(routing.NextVar(index))\n",
    "            route_distance += routing.GetArcCostForVehicle(\n",
    "                previous_index, index, vehicle_id\n",
    "            )\n",
    "        one_var = dim_one.CumulVar(index)\n",
    "        two_var = dim_two.CumulVar(index)\n",
    "        plan_output += (\n",
    "            f\"N:{manager.IndexToNode(index)}\"\n",
    "            f\" one:{solution.Value(one_var)}\"\n",
    "            f\" two:{solution.Value(two_var)}\\n\"\n",
    "        )\n",
    "        plan_output += f\"Distance of the route: {route_distance}m\\n\"\n",
    "        print(plan_output)\n",
    "        max_route_distance = max(route_distance, max_route_distance)\n",
    "    print(f\"Maximum of the route distances: {max_route_distance}m\")\n",
    "\n",
    "\n",
    "\n",
    "def main():\n",
    "    \"\"\"Solve the CVRP problem.\"\"\"\n",
    "    # Instantiate the data problem.\n",
    "    data = create_data_model()\n",
    "\n",
    "    # Create the routing index manager.\n",
    "    manager = pywrapcp.RoutingIndexManager(\n",
    "        len(data[\"distance_matrix\"]), data[\"num_vehicles\"], data[\"depot\"]\n",
    "    )\n",
    "\n",
    "    # Create Routing Model.\n",
    "    routing = pywrapcp.RoutingModel(manager)\n",
    "\n",
    "\n",
    "    # Create and register a transit callback.\n",
    "    def distance_callback(from_index, to_index):\n",
    "        \"\"\"Returns the distance between the two nodes.\"\"\"\n",
    "        # Convert from routing variable Index to distance matrix NodeIndex.\n",
    "        from_node = manager.IndexToNode(from_index)\n",
    "        to_node = manager.IndexToNode(to_index)\n",
    "        return data[\"distance_matrix\"][from_node][to_node]\n",
    "\n",
    "    transit_callback_index = routing.RegisterTransitCallback(distance_callback)\n",
    "\n",
    "    # Define cost of each arc.\n",
    "    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n",
    "\n",
    "    # Add Distance constraint.\n",
    "    dimension_name = \"Distance\"\n",
    "    routing.AddDimension(\n",
    "        transit_callback_index,\n",
    "        0,  # no slack\n",
    "        3_000,  # vehicle maximum travel distance\n",
    "        True,  # start cumul to zero\n",
    "        dimension_name,\n",
    "    )\n",
    "    distance_dimension = routing.GetDimensionOrDie(dimension_name)\n",
    "    distance_dimension.SetGlobalSpanCostCoefficient(10)\n",
    "\n",
    "    # Max Node value Constraint.\n",
    "    # Dimension One will be used to compute the max node value up to the node in\n",
    "    # the route and store the result in the SlackVar of the node.\n",
    "    routing.AddConstantDimensionWithSlack(\n",
    "        0,  # transit 0\n",
    "        42 * 16,  # capacity: be able to store PEAK*ROUTE_LENGTH in worst case\n",
    "        42,  # slack_max: to be able to store peak in slack\n",
    "        True,  #  Fix StartCumulToZero not really matter here\n",
    "        \"One\",\n",
    "    )\n",
    "    dim_one = routing.GetDimensionOrDie(\"One\")\n",
    "\n",
    "    # Dimension Two will be used to store the max node value in the route end node\n",
    "    # CumulVar so we can use it as an objective cost.\n",
    "    routing.AddConstantDimensionWithSlack(\n",
    "        0,  # transit 0\n",
    "        42 * 16,  # capacity: be able to have PEAK value in CumulVar(End)\n",
    "        42,  # slack_max: to be able to store peak in slack\n",
    "        True,  #  Fix StartCumulToZero YES here\n",
    "        \"Two\",\n",
    "    )\n",
    "    dim_two = routing.GetDimensionOrDie(\"Two\")\n",
    "\n",
    "    # force depot Slack to be value since we don't have any predecessor...\n",
    "    for v in range(manager.GetNumberOfVehicles()):\n",
    "        start = routing.Start(v)\n",
    "        dim_one.SlackVar(start).SetValue(data[\"value\"][0])\n",
    "        routing.AddToAssignment(dim_one.SlackVar(start))\n",
    "\n",
    "        dim_two.SlackVar(start).SetValue(data[\"value\"][0])\n",
    "        routing.AddToAssignment(dim_two.SlackVar(start))\n",
    "\n",
    "    # Step by step relation\n",
    "    # Slack(N) = max( Slack(N-1) , value(N) )\n",
    "    solver = routing.solver()\n",
    "    for node in range(1, 17):\n",
    "        index = manager.NodeToIndex(node)\n",
    "        routing.AddToAssignment(dim_one.SlackVar(index))\n",
    "        routing.AddToAssignment(dim_two.SlackVar(index))\n",
    "        test = []\n",
    "        for v in range(manager.GetNumberOfVehicles()):\n",
    "            previous_index = routing.Start(v)\n",
    "            cond = routing.NextVar(previous_index) == index\n",
    "            value = solver.Max(dim_one.SlackVar(previous_index), data[\"value\"][node])\n",
    "            test.append((cond * value).Var())\n",
    "        for previous in range(1, 17):\n",
    "            previous_index = manager.NodeToIndex(previous)\n",
    "            cond = routing.NextVar(previous_index) == index\n",
    "            value = solver.Max(dim_one.SlackVar(previous_index), data[\"value\"][node])\n",
    "            test.append((cond * value).Var())\n",
    "        solver.Add(solver.Sum(test) == dim_one.SlackVar(index))\n",
    "\n",
    "    # relation between dimensions, copy last node Slack from dim ONE to dim TWO\n",
    "    for node in range(1, 17):\n",
    "        index = manager.NodeToIndex(node)\n",
    "        values = []\n",
    "        for v in range(manager.GetNumberOfVehicles()):\n",
    "            next_index = routing.End(v)\n",
    "            cond = routing.NextVar(index) == next_index\n",
    "            value = dim_one.SlackVar(index)\n",
    "            values.append((cond * value).Var())\n",
    "        solver.Add(solver.Sum(values) == dim_two.SlackVar(index))\n",
    "\n",
    "    # Should force all others dim_two slack var to zero...\n",
    "    for v in range(manager.GetNumberOfVehicles()):\n",
    "        end = routing.End(v)\n",
    "        dim_two.SetCumulVarSoftUpperBound(end, 0, 4200)\n",
    "\n",
    "    # Setting first solution heuristic.\n",
    "    search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
    "    search_parameters.first_solution_strategy = (\n",
    "        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC\n",
    "    )\n",
    "    search_parameters.local_search_metaheuristic = (\n",
    "        routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH\n",
    "    )\n",
    "    # search_parameters.log_search = True\n",
    "    search_parameters.time_limit.FromSeconds(5)\n",
    "\n",
    "    # Solve the problem.\n",
    "    solution = routing.SolveWithParameters(search_parameters)\n",
    "\n",
    "    # Print solution on console.\n",
    "    if solution:\n",
    "        print_solution(data, manager, routing, solution)\n",
    "    else:\n",
    "        print(\"No solution found !\")\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
